<template>
  <div class="container">
    <el-row class="header">
      <el-col class="asd" :span="16" align="left">
        <el-input v-model="data.params.projectName" placeholder="项目名称/编号" style="width: 200px; margin-right: 15px" />

        <el-button  @click="search()" class="ordinary">搜索</el-button>
      </el-col>

      <el-col :span="8" align="right">
<!--        <el-button class="ordinary" @click="handleExport()" v-limit="'XMZX:SZXMLXPS:LDBZHS:EXPORT'">批量导出</el-button>-->
        <el-button class="ordinary" @click="handleExport1()" v-limit="'XMZX:SZXMLXPS:LDBZHS:EXPORT'"> 批量导出</el-button>
        <el-button type="primary" @click="handleExamine()" v-limit="'XMZX:SZXMLXPS:LDBZHS:EXANDAPP'">审批</el-button>
      </el-col>
    </el-row>

    <Table class="table_" :hasOperate="true" :loading="data.isLoading" :table-arr="data.allTableData" :pagination="data.page"
      :columns="data.columns" @selectList="getCurrentList" @delectTable="delectIds"    @row-click="handleRowClick"   >
      <!-- <template #operate="{ row }">
          <el-button size="small" class="ordinary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" class="ordinary" @click="handleDetail(row)">详情</el-button>
        </template> -->
    </Table>
    <div class="example-pagination-block">
            <el-pagination
              :current-page="data.params.current"
              :page-size="data.params.size"
              :page-sizes="[10, 20, 30, 40,50,100]"
              background
              layout="prev, pager, next ,total,sizes,jumper"
              :total="data.page.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
    </div>
    <!-- 项目变更信息表格 -->
    <el-dialog v-model="data.editDialog" width="72%" top="10vh" @close="handleClose" :title="data.currentHandle"
      :close-on-click-modal="false">
      <Information></Information>
      <!-- <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.editDialog = false">关闭</el-button>
            <el-button v-if="data.currentHandle !== '变更详情'" type="primary" @click="handleSave()"
              >保存</el-button
            >
          </span>
        </template> -->
    </el-dialog>

    <!-- 项目变更审批表格 -->
    <el-dialog v-model="data.examineDialog" width="50%" top="10vh" title="项目变更审批" :close-on-click-modal="false">
      <examine v-if="data.examineDialog"></examine>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handlePass()">审批通过</el-button>
          <el-button type="danger" @click="handleNoPass()">审批不通过</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="data.openDetail" width="60%" :show-close="true" style="min-height: 200px;">
      <template #title>
        <div class="my-header" >
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <detailDialog :detailData="data.detailData" :lookId="data.lookId"/>
            </el-tab-pane>
            <el-tab-pane label="项目经费预算" name="2">
              <el-table :data="data.tableBudget" border>
                <el-table-column type="index" label="序号" width="50" />
                <el-table-column prop="costCategoryName" label="费用分类"></el-table-column>
                <el-table-column prop="subjectName" label="科目名称"></el-table-column>
                <el-table-column prop="amount" label="金额(万元)"></el-table-column>
                <el-table-column prop="remark" label="备注"></el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane v-if="data.approvalFormalExamination.modifyTime"  label="审批详情" name="approvalInfo">
              <el-form class="inline-form" label-position="top" status-icon label-width="140px">
                <el-form-item label="审查结果："> {{data.approvalFormalExamination.status}} </el-form-item>
                <el-form-item label="审查人：">  {{data.approvalFormalExamination.modifyUsername}} </el-form-item>
                <el-form-item label="审查时间："> {{data.approvalFormalExamination.modifyTime}} </el-form-item>
                <el-form-item label="审查意见：">
                  <el-input type="textarea" disabled v-model="data.approvalFormalExamination.permissionReviewComments"></el-input>
                </el-form-item>
                <el-form-item label="附件："> 
                  <template v-if="data.approvalFormalExamination.files && data.approvalFormalExamination.files.length">
                     <div v-for="(file , i) in data.approvalFormalExamination.files" :key="'fiels' + i" style="margin-right: 10px">
                      <el-link type="primary"  :href="file.url" target="_blank">{{file.name}}</el-link>
                     </div>
                  </template>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>

      </template>
      <template #footer>
        <span style="text-align: center;">
          <el-button @click="data.openDetail = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>


    <!-- 导出字段选择 -->
    <Export
        :detailList="data.detailList"
        :showing="data.exportDialog"
        @close="closeExport"
        @handle-filed="handleFiled"
    ></Export>

  </div>
</template>

<script lang="ts">
import { reactive, ref } from 'vue'
import Information from './components/information.vue'
import tableData from './tableHeader.json'

import { getChangeList } from '../../api/meeting-leaders'
import { getOrgTree } from '../../api/org'
import Catalog from '../../components/Catalog/index.vue'
import Table from '../../components/table/table.vue'
import examine from './components/examine.vue'
import detailDialog from './components/detailDialog.vue'
// import { ElMessageBox } from 'element-plus'

import {ElMessage, ElMessageBox} from 'element-plus'
import { useStore } from 'vuex'
import { examineChange, exportProjectList,exportProjectList1 } from '../../api/meeting-leaders'
import Export from '@/views/project/components/Export/index.vue'
import {getExportExpertReview1, hadDetail} from "@/views/science/api/digit";

export default {
  components: {
    Catalog,
    Table,
    Information,
    examine,Export,detailDialog,
  },
  setup() {
    const store = useStore()
    const activeName = ref('1')
    let data = reactive({
      defaultExpandedKeys: [],
      tableTreeData: [],
      currentHandle: '科技研发项目新增',
      params: {
        createOrgId: '',
        projectName: '',
        projectCategory: '',
        size:10,
        current: 1,
      },
      isLoading: false,
      allTableData: [],
      columns: tableData.platformTableHeader,
      page: { page: 1, limit: 10, total: 0 },
      currentList: [],
      editDialog: false,
      examineDialog: false,
      currentRow: {},
      ids:[],
      exportDialog: false,
      detailList: [] as any,
      //详情
      openDetail:false,
      detailData:{},
      tableBudget:[],//经费预算
      approvalFormalExamination: {
        modifyUsername: '',
        modifyTime: '',
        permissionReviewComments: '',
        status: '',
        files: []
      }
    });
    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      // let sdt = selectArr.map((el) => el.id);
      // let sdt = data.currentList.map((el) => el.id);
      // let sdt = data.currentList.map((el) => el.id);
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          // getExportExpertReview1({ ...data.params, ids: data.ids , headList: arr}, "数字化领导班子会审");
          exportProjectList1({ ...data.params,ids:data.ids, headList: arr}, "数字化领导班子会审");
          console.log('批量导出')
          data.exportDialog = false;


        })
      }
    }
    const handleExport1 = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'projectCategory', title: '项目类别' },
        { fieldName: 'projectStartTime', title: '项目开始时间' },
        { fieldName: 'projectEndTime', title: '预计完成时间' },
        // { fieldName: 'projectLeader', title: '项目负责人' },
        { fieldName: 'applyUnit', title: '申报单位' },
        // { fieldName: 'projectLeader', title: '项目负责人' },
        // { fieldName: 'contactPhone', title: '联系电话' },
        // { fieldName: 'completionPeriod', title: '完成年限' },
        { fieldName: 'totalBudget', title: '总投资(万元)' },
        // { fieldName: 'applyBudget', title: '申请中咨拨款(万元)' },
        { fieldName: 'applyDate', title: '申报日期' },
        { fieldName: 'summarize', title: '概述' },
        { fieldName: 'demandAnalysis', title: '现状及需求分析' },
        { fieldName: 'feasibilityNalysis', title: '项目必要性和可行性分析' },
        { fieldName: 'implementationPlan', title: '项目内容和实施方案' },
        { fieldName: 'projectSchedule', title: '项目进度计划' },
        { fieldName: 'projectCostEstimation', title: '项目费用估算' },
        { fieldName: 'projectBenefitAnalysis', title: '项目效益分析' },
        { fieldName: 'riskCountermeasure', title: '风险及对策' },
        { fieldName: 'stu', title: '状态' },
        /*          { fieldName: 'researchContent', title: '主要研究内容' },
                 { fieldName: 'economicIndicator', title: '主要技术经济指标' },
                 { fieldName: 'intellectualProperty', title: '创新点及可能获得的成果和知识产权' },
                 { fieldName: 'projectBackground', title: '立项背景(包括项目背景、项目概况、研究的必要性等)' },
                 { fieldName: 'feasibilityAnalysis', title: '国内外研究概况及可行性分析' },
                 { fieldName: 'technicalIndex', title: '项目研究的主要内容及技术指标' },
                 { fieldName: 'technicalRoute', title: '项目研究的技术路线' },
                 { fieldName: 'benefitForecast', title: '推广应用前景及经济效益预测' },
                 { fieldName: 'unitDivision', title: '申报单位和协作单位及分工' },
                 { fieldName: 'economicIndicator', title: '主要技术经济指标' },
                 { fieldName: 'intellectualProperty', title: '创新点及可能获得的成果和知识产权' },*/
      ]
    }
    interface Config {
      id: string;
    }
    let selectArr: Config[] = reactive([]);
    const handleSelectionChange = (val) => {
      selectArr = val;
    },
        changeFormDetail = {
        id: '7dd3eb5d608544789508de64077b1d5c',
        projectCategory: null,
        projectCategoryName: null,
        projectName: null,
        projectType: null,
        projectYear: null,
        affiliatedUnitName: null,
        startTime: null,
        endTime: null,
        projectNumber: null,
        createOrgId: null,
        projectId: 'string',
        type: null,
        typeName: null,
        requestFlag: 'string',
        beforeContent: 'string',
        afterContent: 'string',
        description: 'string',
        status: '1',
        statusName: null,
        applicantId: 'string',
        applicantName: null,
        applicationTime: null,
        leaderReviewComments: null,
        attachment: null,
        current: null,
        size: null,
      }
    const options = [
      {
        value: 'Option1',
        label: 'Option1',
      },
      {
        value: 'Option2',
        label: 'Option2',
      },
      {
        value: 'Option3',
        label: 'Option3',
      },
    ]
      //分页操作
    const handleSizeChange = (val) =>{
      data.params.current = 1
      data.params.size = val
      onSearch()
    }

    const handleCurrentChange = (val) =>{
      data.params.current = val
      onSearch()
    }
    const onSearch = async () => {
      data.isLoading = true
      getChangeList(data.params).then((res) => {
        data.isLoading = false
        let records = res.data.data
        records.records.map((item) => {
          switch(item.status){
              case 0:item.status = '草稿';break;
              case 1:item.status = '待提交';break;
              case 2:item.status = '待专家评审';break;
              case 3:item.status = '专家评审未通过';break;
              case 4:item.status = '领导班子会审不通过';break;
              case 5:item.status = '待领导班子会审';break;
              case 6:item.status = '待批准';break;
              case 7:item.status = '批准立项';break;
              case 8:item.status = '立项拒绝';break;
          }
        })
        data.allTableData = records.records
        data.page.total = res.data.data.total
      })
    }
    onSearch()
    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.currentList = currentList
    }
    const delectIds = (ids) => {
      console.log("ids",ids)
      data.ids = ids
      console.log("data.ids",data.ids)

    }
    const handleRowClick = (row) => {
      handleEdit(row)
    }
    //-------------------------详情
    const handleEdit = (row) => {
      // data.detailId = row.id
      data.isLoading = true
      hadDetail({id:row.id}).then(res =>{
        console.log('详情',res);
        data.detailData = res.data.data.info
        data.tableBudget = res.data.data.contractBudgetList
        data.approvalFormalExamination.modifyUsername = res.data.data.info.modifyUsername
        data.approvalFormalExamination.modifyTime = res.data.data.info.modifyTime
        data.approvalFormalExamination.permissionReviewComments =res.data.data.info.permissionReviewComments
        data.approvalFormalExamination.status = row.status
        let info = res.data.data.info
        let file = info.permissionFilePath ? JSON.parse(info.permissionFilePath) : []
        data.approvalFormalExamination.files = file
        console.log(data.approvalFormalExamination)
        
        data.isLoading = false
        data.openDetail = true
      })
      // store.commit('innovativeTalents/getRowId', row.id)
    }

    getOrgTree().then((res) => {
      data.tableTreeData = res.data.data
      // this.treeSelectData[0].children = this.dictCatalog
      data.defaultExpandedKeys = (data.tableTreeData as any).map((item) => item.id)
    })

    const defaultProps = {
      children: 'children',
      label: 'label',
    }
    const orgSearch = (org) => {
      data.page.page = 1
      data.params.createOrgId = org.id
      console.log(data.params)
      onSearch()
    }
    const search = () => {
      data.page.page = 1
      onSearch()
    }
/*    const handleEdit = (row) => {
      data.currentHandle = '科技研发项目编辑'
      data.editDialog = true
      data.currentRow = row
      console.log(row, 'row')
      store.state.projectCenter.form = row
    }*/
    const handleDetail = (row) => {
      data.currentHandle = '科技研发项目详情'
      data.editDialog = true
      data.currentRow = row
    }


    const handleExport = () => {
      exportProjectList(data.params)
    }
    const handleSave = () => {
      // detailData(row.id)
      data.editDialog = false
    }
    const examineForm = store.state.projectCenter.examineForm
    const handleExamine = () => {
      console.log(data.currentList.length, 'data.currentList.length')
      console.log(data.currentList, 'data.currentList')
      if( (data.currentList[0] as any).status == '领导班子会审不通过' ){
        ElMessage({
          message: '该项目已被不通过，无法再次审批',
          type: 'warning',
        })
        return
      }else if ((data.currentList[0] as any).status != '待领导班子会审' ){
        ElMessage({
          message: '请选择处于领导班子会审的数据进行审批',
          type: 'warning',
        })
        return
      }
      if (data.currentList.length == 1) {
        data.examineDialog = true
        examineForm.id = (data.currentList[0] as any).id
        examineForm.leaderFileName = '领导审批文件'
      } else {
        ElMessage({
          message: '请选择一个变更记录进行审批',
          type: 'warning',
        })
      }

    }
    const handlePass = () => {
      console.log(examineForm.leaderReviewComments, 'examineForm.leaderReviewComments')
      if (!examineForm.leaderReviewComments) {
        ElMessage({
          message: '请输入审批意见',
          type: 'warning',
        })
        return
      }
      examineForm.status = 6
      examineChange([{
        ...examineForm,
      }]).then((res) => {
        console.log(res)
        if (res.data.code == 200) {
          ElMessage({
            message: '操作成功',
            type: 'success',
          })
          data.examineDialog = false
          onSearch()
        }
      })
    }
    const handleNoPass = () => {
      if (!examineForm.leaderReviewComments) {
        ElMessage({
          message: '请输入审批意见',
          type: 'warning',
        })
        return
      }
      examineForm.status = 4
      examineChange([{
        ...examineForm,
      }]).then((res) => {
        console.log(res)
        if (res.data.code == 200) {
          ElMessage({
            message: '操作成功',
            type: 'success',
          })
          data.examineDialog = false
          onSearch()
        }
      })
    }
    const handleClose = () => {
      data.editDialog = false
      activeName.value = '1'
    }

    return {
      store,
      data,
      activeName,
      defaultProps,
      options,
      changeFormDetail,
      getCurrentList,
      onSearch,
      handleEdit,
      handleDetail,
      handleExamine,
      handleSave,
      handleClose,
      handleExport,
      orgSearch,
      search,
      handlePass,
      handleNoPass,
      handleSizeChange,
      handleCurrentChange,
      delectIds,
      closeExport,
      handleFiled,
      handleExport1,
      handleRowClick,

    }
  },
}
</script>

<style lang="scss">
.table_{
  .el-pagination {
      display: none;
    }
}
</style>
<style lang="scss" scoped>
.example-pagination-block {
  margin-top: 15px;
  text-align: center;
}

:deep(.el-pagination .btn-next .el-icon) {
  margin: 0 auto;
}
.container {
  background-color: white;
  // padding: 0 20px 20px;
  padding: 20px;
}

.project {
  display: flex;

  .tree {
    width: 20%;
  }

  .data {
    width: 80%;
  }
}

.el-col {
  // line-height: 60px;
}

.pageName {
  font-weight: 700;
}

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

/deep/.demo-tabs>.el-tabs__content {
  max-height: 500px;
  overflow-y: scroll;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}

/deep/.demo-tabs>.el-tabs__content::-webkit-scrollbar {
  display: none;
  /* Chrome Safari */
}

:deep(.el-dialog__body) {
  display: block;
  padding: 10px 20px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid rgb(234, 230, 230);
}

.inline-form::v-deep {
  .el-form-item {
    display: flex;
  }
  .el-form-item__label {
    width: 120px;
    text-align: right;
  }
  .el-form-item__content {
    opacity: .8;
  }
}
</style>
